<template>
  <div class="app-container">
    <!-- 引入物料选择器组件 -->
    <MaterialSelector 
      ref="materialSelectorRef" 
      v-model:visible="materialSelectorVisible" 
      @select="handleMaterialSelected" 
    />
    
    <!-- 引入仓库选择器组件 -->
    <WarehouseSelector
      ref="warehouseSelectorRef"
      v-model:visible="warehouseSelectorVisible"
      @select="handleWarehouseSelected"
    />

    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="申请编号" prop="applyCode">
        <el-input
          v-model="queryParams.applyCode"
          placeholder="请输入申请编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="申请类型" prop="applyType">
        <el-select v-model="queryParams.applyType" placeholder="请选择申请类型" clearable>
          <el-option
            v-for="dict in mwm_inbound_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in apply_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="供应商" prop="supplierId">
        <el-select
          v-model="queryParams.supplierId"
          placeholder="请选择供应商"
          clearable
          @keyup.enter="handleQuery"
        >
          <el-option
            v-for="item in supplierOptions"
            :key="item.supplierId"
            :label="item.supplierName"
            :value="item.supplierId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="申请人" prop="applyUserId">
        <el-select
          v-model="queryParams.applyUserId"
          placeholder="请选择申请人"
          clearable
          @keyup.enter="handleQuery"
        >
          <el-option
            v-for="item in userOptions"
            :key="item.userId"
            :label="item.userName"
            :value="item.userId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="申请时间" style="width: 308px">
        <el-date-picker
          v-model="daterangeApplyTime"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="审核人" prop="auditUserId">
        <el-select
          v-model="queryParams.auditUserId"
          placeholder="请选择审核人"
          clearable
          @keyup.enter="handleQuery"
        >
          <el-option
            v-for="item in userOptions"
            :key="item.userId"
            :label="item.userName"
            :value="item.userId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="审核时间" style="width: 308px">
        <el-date-picker
          v-model="daterangeAuditTime"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['tas:MaterialInboundApply:add']"
        >新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['tas:MaterialInboundApply:edit']"
        >修改</el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['tas:MaterialInboundApply:remove']"
        >删除</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['tas:MaterialInboundApply:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="MaterialInboundApplyList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="申请ID" align="center" prop="applyId" />
      <el-table-column label="申请编号" align="center" prop="applyCode" />
      <el-table-column label="申请类型" align="center" prop="applyType">
        <template #default="scope">
          <dict-tag :options="mwm_inbound_type" :value="scope.row.applyType"/>
        </template>
      </el-table-column>
      <el-table-column label="申请人" align="center" prop="applyUserName" />
      <el-table-column label="申请时间" align="center" prop="applyTime" width="180" />
      <el-table-column label="供应商" align="center" prop="supplierName" />
      <el-table-column label="审核人" align="center" prop="auditUserName" />
      <el-table-column label="审核时间" align="center" prop="auditTime" width="180" />
      <el-table-column label="审核意见" align="center" prop="auditOpinion" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="apply_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button 
            link 
            type="primary" 
            icon="Edit" 
            @click="handleUpdate(scope.row)" 
            v-hasPermi="['tas:MaterialInboundApply:edit']"
            v-if="scope.row.status === '4' || scope.row.status === '2'"
          >修改</el-button>
          
          <el-button 
            link 
            type="success" 
            icon="Check" 
            @click="handleSubmit(scope.row)" 
            v-hasPermi="['tas:MaterialInboundApply:edit']"
            v-if="scope.row.status === '4' || scope.row.status === '2'"
          >提交</el-button>
          
          <el-button 
            link 
            type="danger" 
            icon="Delete" 
            @click="handleDelete(scope.row)" 
            v-hasPermi="['tas:MaterialInboundApply:remove']"
            v-if="scope.row.status === '4' || scope.row.status === '2'"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改物料入库申请对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="MaterialInboundApplyRef" :model="form" :rules="rules" label-width="100px" :inline="true">
        <el-form-item label="申请编号" prop="applyCode">
          <el-input v-model="form.applyCode" placeholder="请输入申请编号" disabled/>
        </el-form-item>
        <el-form-item label="申请类型" prop="applyType">
          <el-select v-model="form.applyType" placeholder="请选择申请类型" @change="handleApplyTypeChange">
            <el-option
              v-for="dict in mwm_inbound_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态" disabled>
            <el-option
              v-for="dict in apply_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="供应商" prop="supplierId" v-if="String(form.applyType) === '1'">
          <el-select
            v-model="form.supplierId"
            placeholder="请选择供应商"
            filterable
          >
            <el-option
              v-for="item in supplierOptions"
              :key="item.supplierId"
              :label="item.supplierName"
              :value="item.supplierId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="申请人" prop="applyUserId">
          <el-select v-model="form.applyUserId" placeholder="请选择申请人" filterable>
            <el-option
              v-for="item in userOptions"
              :key="item.userId"
              :label="item.userName"
              :value="item.userId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="申请时间" prop="applyTime">
          <el-date-picker clearable
            v-model="form.applyTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择申请时间"
            disabled
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="审核人" prop="auditUserId" v-if="form.applyId">
          <el-input v-model="form.auditUserName" placeholder="审核人" disabled />
        </el-form-item>
        <el-form-item label="审核时间" prop="auditTime" v-if="form.applyId">
          <el-input v-model="form.auditTime" placeholder="审核时间" disabled />
        </el-form-item>
        <el-form-item label="审核意见" prop="auditOpinion" v-if="form.applyId">
          <el-input v-model="form.auditOpinion" type="textarea" placeholder="审核意见" disabled />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-divider content-position="center">物料明细</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="Plus" @click="handleAddMaterialInboundApplyDetail">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="Delete"  @click="handleDeleteMaterialInboundApplyDetail">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="materialInboundApplyDetailList" :row-class-name="rowMaterialInboundApplyDetailIndex" @selection-change="handleMaterialInboundApplyDetailSelectionChange" ref="materialInboundApplyDetail">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="物料" prop="materialId" width="180">
            <template #default="scope">
              <div class="wuliao-xuanze">
                <el-input 
                  v-model="scope.row.materialName" 
                  placeholder="请选择物料" 
                  readonly 
                  class="wuliao-input"
                  disabled
                >
                  <template #append>
                    <el-button @click="openMaterialSelector(scope.$index)">选择</el-button>
                  </template>
                </el-input>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="数量" align="center" prop="quantity" width="174">
            <template #default="scope">
              <el-input-number v-model="scope.row.quantity" :min="1" placeholder="数量" />
            </template>
          </el-table-column>
          <el-table-column label="单位" align="center" prop="unit" width="100" />
          <el-table-column label="仓库" prop="warehouseId" width="180">
            <template #default="scope">
              <div class="cangku-xuanze">
                <el-input 
                  v-model="scope.row.warehouseName" 
                  placeholder="请选择仓库" 
                  readonly 
                  class="cangku-input"
                  disabled
                >
                  <template #append>
                    <el-button @click="openWarehouseSelector(scope.$index)">选择</el-button>
                  </template>
                </el-input>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="库位" prop="locationId" width="120">
            <template #default="scope">
              <el-input disabled
                v-model="scope.row.locationName"
                placeholder="请输入库位名称"
                :disabled="!scope.row.warehouseId"
              />
            </template>
          </el-table-column>
          <el-table-column label="备注" prop="remark" width="120">
            <template #default="scope">
              <el-input v-model="scope.row.remark" type="textarea" placeholder="请输入备注" />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="MaterialInboundApply">
import { 
  listMaterialInboundApply, 
  getMaterialInboundApply, 
  delMaterialInboundApply, 
  addMaterialInboundApply, 
  updateMaterialInboundApply, 
  listUserAll, 
  listSupplier,  
} from "@/api/tas/MaterialInboundApply";
import request from '@/utils/request';
import MaterialSelector from "@/components/MaterialSelector/index.vue";
import WarehouseSelector from "@/components/WarehouseSelector/index.vue";

const { proxy } = getCurrentInstance();
const { mwm_inbound_type, apply_status } = proxy.useDict('mwm_inbound_type', 'apply_status');

const MaterialInboundApplyList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const daterangeApplyTime = ref([]);
const daterangeAuditTime = ref([]);
const materialInboundApplyDetailList = ref([]);
const checkedMaterialInboundApplyDetail = ref([]);

// 用户选项
const userOptions = ref([]);
const supplierOptions = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    applyCode: null,
    applyType: null,
    status: null,
    applyUserId: null,
    applyTime: null,
    auditUserId: null,
    auditTime: null,
    supplierId: null,
  },
  rules: {
    applyCode: [{ required: true, message: "申请编号不能为空", trigger: "blur" }],
    applyType: [{ required: true, message: "申请类型不能为空", trigger: "change" }],
    status: [{ required: true, message: "状态不能为空", trigger: "change" }],
    supplierId: [{ 
      required: true, 
      message: "供应商不能为空", 
      trigger: "change",
      validator: (rule, value, callback) => {
        if (form.value.applyType === '1' && !value) {
          callback(new Error("采购入库需要选择供应商"));
        } else {
          callback();
        }
      }
    }],
    applyTime: [{ required: true, message: "申请时间不能为空", trigger: "blur" }],
  }
});

const { queryParams, form, rules } = toRefs(data);

// 物料选择器相关变量
const materialSelectorVisible = ref(false);
const materialSelectorRef = ref(null);
const currentEditingIndex = ref(-1); // 记录当前编辑的行索引

// 仓库选择器相关变量
const warehouseSelectorVisible = ref(false);
const warehouseSelectorRef = ref(null);
const currentEditingType = ref(''); // 'material' 或 'warehouse'

/** 查询物料入库申请列表 */
function getList() {
  loading.value = true;
   // 先添加申请时间范围
  let params = proxy.addDateRange(queryParams.value, daterangeApplyTime.value, "ApplyTime");
  // 再添加审核时间范围
  params = proxy.addDateRange(params, daterangeAuditTime.value, "AuditTime");
  
  listMaterialInboundApply(params).then(response => {
    MaterialInboundApplyList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    applyId: null,
    applyCode: null,
    applyType: null,
    status: "4",
    applyUserId: null,
    applyTime: null,
    auditUserId: null,
    auditTime: null,
    auditOpinion: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null,
    supplierId: null, // 供应商ID
  };
  materialInboundApplyDetailList.value = [];
  proxy.resetForm("MaterialInboundApplyRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeApplyTime.value = [];
  daterangeAuditTime.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.applyId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

// 添加生成申请编号的函数
function generateApplyCode() {
  const date = new Date();
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const dateStr = `${year}${month}${day}`;
  
  const randomNum = Math.floor(1000 + Math.random() * 9000);
  
  return `MIA${dateStr}${randomNum}`;
}

// 修改新增按钮操作函数
function handleAdd() {
  reset();
  form.value.applyCode = generateApplyCode();
  form.value.applyTime = new Date().toISOString().split('T')[0];
  form.value.status = "4";

  open.value = true;
  title.value = "添加物料入库申请";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  const _applyId = row.applyId || ids.value;
  
  if (supplierOptions.value.length === 0) {
    listSupplier().then(response => {
      console.log('供应商列表:', response);
      supplierOptions.value = response.data || response.rows;
      console.log('供应商列表:', supplierOptions.value);
      loadApplyDetail(_applyId);
    });
  } else {
    loadApplyDetail(_applyId);
  }
}

// 添加物料、仓库、库位批量加载函数
function loadDetailRelatedInfo() {
  // 如果明细为空，不执行
  if (!materialInboundApplyDetailList.value || materialInboundApplyDetailList.value.length === 0) {
    return;
  }
  
  // 1. 加载物料信息
  // 使用 listMaterial API 获取物料列表，从 MaterialInboundApply.js 已导入
  request({
    url: '/mwm/inventory/material/getlist',
    method: 'get'
  }).then(response => {
    if (response.code === 200 && response.data) {
      const materials = response.data;
      // 更新物料名称
      materialInboundApplyDetailList.value.forEach(item => {
        if (item.materialId) {
          const material = materials.find(m => m.materialId === item.materialId);
          if (material) {
            item.materialName = material.materialName;
            // 如果单位为空，使用物料默认单位
            if (!item.unit) {
              item.unit = material.unit;
            }
          }
        }
      });
    }
  });
  
  // 2. 加载仓库信息
  // 使用 listWarehouse API 获取仓库列表
  request({
    url: '/mwm/inventory/warehouse/getlist',
    method: 'get'
  }).then(response => {
    if (response.code === 200 && response.data) {
      const warehouses = response.data;
      // 更新仓库名称
      materialInboundApplyDetailList.value.forEach(item => {
        if (item.warehouseId) {
          const warehouse = warehouses.find(w => w.warehouseId === item.warehouseId);
          if (warehouse) {
            item.warehouseName = warehouse.warehouseName;
          }
        }
      });
    }
  });
  
  // 3. 加载库位信息
  // 使用 listLocation API 获取库位列表
  request({
    url: '/mwm/inventory/location/getlist',
    method: 'get'
  }).then(response => {
    if (response.code === 200 && response.data) {
      const locations = response.data;
      // 更新库位名称
      materialInboundApplyDetailList.value.forEach(item => {
        if (item.locationId) {
          const location = locations.find(l => l.locationId === item.locationId);
          if (location) {
            item.locationName = location.locationName;
          }
        }
      });
    }
  });
}

// 修改 loadApplyDetail 函数
function loadApplyDetail(applyId) {
  getMaterialInboundApply(applyId).then(response => {
    let applyData = response.data;
    
    if (applyData.applyType !== null && applyData.applyType !== undefined) {
      applyData.applyType = String(applyData.applyType);
    }
    
    console.log('申请类型:', applyData.applyType);
    console.log('供应商ID:', applyData.supplierId);
    
    form.value = applyData;
    
    console.log('明细数据:', JSON.stringify(applyData.materialInboundApplyDetailList));
    
    if (applyData.materialInboundApplyDetailList && applyData.materialInboundApplyDetailList.length > 0) {
      materialInboundApplyDetailList.value = applyData.materialInboundApplyDetailList.map((item, index) => {
        return {
          ...item,
          index: index + 1,
          materialName: item.materialName || '',
          warehouseName: item.warehouseName || '',
          locationName: item.locationName || ''
        };
      });
      
      // 加载物料、仓库、库位信息
      loadDetailRelatedInfo();
    } else {
      materialInboundApplyDetailList.value = [];
    }
    
    open.value = true;
    title.value = "修改物料入库申请";
    
    proxy.$nextTick(() => {
      if (form.value.applyType === '1' && !form.value.supplierId && applyData.supplierId) {
        form.value.supplierId = applyData.supplierId;
      }
    });
  });
}

/** 表单提交 */
function submitForm() {
  proxy.$refs["MaterialInboundApplyRef"].validate(valid => {
    if (valid) {
      if (materialInboundApplyDetailList.value.length === 0) {
        proxy.$modal.msgError("请添加至少一项物料明细");
        return;
      }
      
      let isDetailValid = true;
      materialInboundApplyDetailList.value.forEach((item, index) => {
        if (!item.materialId || !item.quantity || !item.warehouseId) {
          isDetailValid = false;
          proxy.$modal.msgError(`第 ${index + 1} 行物料信息不完整，需要填写物料、数量和仓库`);
        }
      });
      
      if (!isDetailValid) return;
      
      if (form.value.applyType === '1' && !form.value.supplierId) {
        proxy.$modal.msgError("采购入库申请必须选择供应商");
        return;
      }
      
      form.value.materialInboundApplyDetailList = materialInboundApplyDetailList.value;
      
      if (form.value.applyId != null) {
        updateMaterialInboundApply(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addMaterialInboundApply(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
    const _applyIds = row.applyId || ids.value;
    proxy.$modal.confirm('是否确认删除物料入库申请编号为"' + _applyIds + '"的数据项？').then(function() {
    return delMaterialInboundApply(_applyIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 物料入库申请明细序号 */
function rowMaterialInboundApplyDetailIndex({ row, rowIndex }) {
  row.index = rowIndex + 1;
}

/** 物料入库申请明细添加按钮操作 */
function handleAddMaterialInboundApplyDetail() {
  let obj = {
    applyId: form.value.applyId || "",
    materialId: "",
    materialName: "",
    quantity: "",
    unit: "",
    warehouseId: "",
    warehouseName: "",
    locationId: "",
    locationName: "",
    remark: ""
  };
  materialInboundApplyDetailList.value.push(obj);
}

/** 物料入库申请明细删除按钮操作 */
function handleDeleteMaterialInboundApplyDetail() {
  if (checkedMaterialInboundApplyDetail.value.length == 0) {
    proxy.$modal.msgError("请先选择要删除的物料入库申请明细数据");
  } else {
    const materialInboundApplyDetails = materialInboundApplyDetailList.value;
    const checkedMaterialInboundApplyDetails = checkedMaterialInboundApplyDetail.value;
    materialInboundApplyDetailList.value = materialInboundApplyDetails.filter(function(item) {
      return checkedMaterialInboundApplyDetails.indexOf(item.index) == -1
    });
  }
}

/** 复选框选中数据 */
function handleMaterialInboundApplyDetailSelectionChange(selection) {
  checkedMaterialInboundApplyDetail.value = selection.map(item => item.index)
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('tas/MaterialInboundApply/export', {
    ...queryParams.value
  }, `MaterialInboundApply_${new Date().getTime()}.xlsx`)
}

// 打开仓库选择器
function openWarehouseSelector(index) {
  currentEditingIndex.value = index;
  currentEditingType.value = 'warehouse';
  warehouseSelectorRef.value.open();
}

function handleWarehouseSelected(result) {
  if (result && currentEditingIndex.value >= 0 && currentEditingType.value === 'warehouse') {
    const index = currentEditingIndex.value;
    
    materialInboundApplyDetailList.value[index].warehouseId = result.warehouse.warehouseId;
    materialInboundApplyDetailList.value[index].warehouseName = result.warehouse.warehouseName;
    
    if (result.location) {
      materialInboundApplyDetailList.value[index].locationId = result.location.locationId;
      materialInboundApplyDetailList.value[index].locationName = result.location.locationName;
    } else {
      materialInboundApplyDetailList.value[index].locationId = '';
      materialInboundApplyDetailList.value[index].locationName = '';
    }
    
    currentEditingIndex.value = -1;
    currentEditingType.value = '';
  }
}

function openMaterialSelector(index) {
  currentEditingIndex.value = index;
  currentEditingType.value = 'material';
  materialSelectorRef.value.open();
}

function handleMaterialSelected(material) {
  if (material && currentEditingIndex.value >= 0 && currentEditingType.value === 'material') {
    const index = currentEditingIndex.value;
    materialInboundApplyDetailList.value[index].materialId = material.materialId;
    materialInboundApplyDetailList.value[index].materialName = material.materialName;
    materialInboundApplyDetailList.value[index].unit = material.unit;
    
    currentEditingIndex.value = -1;
    currentEditingType.value = '';
  }
}

function handleApplyTypeChange(val) {
  if (val !== '1') {
    form.value.supplierId = null;
  }
}

// 修改提交功能
function handleSubmit(row) {
  const applyId = row.applyId;
  proxy.$modal.confirm('确认要提交编号为"' + row.applyCode + '"的入库申请吗？提交后将变为待审核状态').then(function() {
    return getMaterialInboundApply(applyId).then(response => {
      const updateObj = {
        applyId: applyId,
        status: '0',  // 将状态更改为"待审核"
        materialInboundApplyDetailList: response.data.materialInboundApplyDetailList
      };
      
      // 直接使用更新API来修改状态
      return updateMaterialInboundApply(updateObj);
    });
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("提交成功");
  }).catch(() => {});
}

onMounted(() => {
  listUserAll().then(response => {
    userOptions.value = response.data;
  });
  listSupplier().then(response => {
    supplierOptions.value = response.data;
  });
  getList();
});
</script>

<style scoped>
.el-divider--horizontal {
  margin: 20px 0;
}

.el-select {
  width: 100%;
}

.wuliao-xuanze,
.cangku-xuanze {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

.wuliao-input,
.cangku-input {
  width: 100%;
}
</style>
